<template>
  <el-card>
    <el-form :inline="true" class="user-form">
      <el-form-item label="用户名">
        <el-input placeholder="请输入用户名" v-model="keyword"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getUserInfo(1)">搜索</el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card style="margin: 10px 0">
    <el-button type="primary" @click="addUser">添加</el-button>

    <el-popconfirm
      :title="`你确定要批量删除吗?`"
      width="200px"
      @confirm="patchDelete"
      :hide-after="0"
    >
      <template #reference>
        <el-button type="danger" :disabled="selectUser.length == 0">
          批量删除
        </el-button>
      </template>
    </el-popconfirm>
    <el-table
      border
      style="margin: 10px 0"
      :data="userInfo"
      @selection-change="handleChange"
    >
      <el-table-column type="selection" align="center"></el-table-column>
      <el-table-column label="#" align="center" type="index"></el-table-column>
      <el-table-column label="id" align="center" prop="id"></el-table-column>
      <el-table-column
        label="用户名字"
        align="center"
        prop="username"
      ></el-table-column>
      <el-table-column
        label="用户名称"
        align="center"
        prop="name"
      ></el-table-column>
      <el-table-column
        label="用户角色"
        align="center"
        prop="roleName"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
      ></el-table-column>
      <el-table-column
        label="更新时间"
        align="center"
        prop="updateTime"
      ></el-table-column>
      <el-table-column label="操作" width="350px" align="center">
        <template #default="{ row }">
          <el-button type="primary" icon="User" @click="setRole(row)">
            分配角色
          </el-button>
          <el-button type="warning" icon="Edit" @click="editUser(row)">
            编辑
          </el-button>
          <el-popconfirm
            :title="`你确定删除${row.username}?`"
            width="200px"
            @confirm="deleteUser(row.id)"
            :hide-after="0"
          >
            <template #reference>
              <el-button type="danger" icon="Delete">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[10, 20, 50, 100]"
      :background="true"
      layout="sizes, prev, pager, next, ->, jumper, total"
      :total="total"
      @current-change="getUserInfo"
      @size-change="handler"
    />
  </el-card>

  <el-drawer v-model="drawer">
    <template #header>
      <h4>{{ userParams.id ? '修改用户' : '添加用户' }}</h4>
    </template>
    <template #default>
      <el-form :model="userParams" :rules="rules" ref="formRef">
        <el-form-item label="用户姓名" prop="username">
          <el-input
            placeholder="请你输入用户姓名"
            v-model="userParams.username"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" prop="name">
          <el-input
            placeholder="请你输入用户昵称"
            v-model="userParams.name"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password" v-if="!userParams.id">
          <el-input
            placeholder="请你输入用户密码"
            v-model="userParams.password"
          ></el-input>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="save">确认</el-button>
      </div>
    </template>
  </el-drawer>

  <!-- 抽屉结构:用户某一个已有的账号进行职位分配 -->
  <el-drawer v-model="drawer1">
    <template #header>
      <h4>分配角色(职位)</h4>
    </template>
    <template #default>
      <el-form>
        <el-form-item label="用户姓名">
          <el-input v-model="userParams.username" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="职位列表">
          <el-checkbox
            @change="handleCheckAllChange"
            v-model="checkAll"
            :indeterminate="isIndeterminate"
          >
            全选
          </el-checkbox>
          <!-- 显示职位的的复选框 -->
          <el-checkbox-group
            v-model="userRole"
            @change="handleCheckedCitiesChange"
          >
            <el-checkbox
              v-for="(role, index) in allRole"
              :key="index"
              :label="role"
            >
              {{ role.roleName }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="drawer1 = false">取消</el-button>
        <el-button type="primary" @click="confirmClick">确定</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { nextTick, onMounted, reactive, ref } from 'vue'
import {
  reqAddOrUpdateUser,
  reqAllRole,
  reqRemoveUser,
  reqSelectUser,
  reqSetUserRole,
  reqUserInfo,
} from '@/api/acl/user'
import { SetRoleData, User } from '@/api/acl/user/type.ts'
import { ElMessage } from 'element-plus'
import useUserStore from '@/store/modules/user.ts'
import useLayoutStore from '@/store/modules/layout.ts'
import { useRoute, useRouter } from 'vue-router'
let $router = useRouter()
let $route = useRoute()
let userStore = useUserStore()
let layoutStore = useLayoutStore()
let currentPage = ref(1)
let pageSize = ref(10)
let total = ref(0)
let keyword = ref('')
let drawer = ref(false)
let drawer1 = ref(false)
let checkAll = ref(false)
let isIndeterminate = ref(true)
let formRef = ref<any>()
let userRole = ref<any>([])
let allRole = ref<any>([])

let userInfo = ref<User[]>([])
onMounted(() => {
  getUserInfo()
})
//收集用户信息的响应式数据
let userParams = reactive<User>({
  username: '',
  name: '',
  password: '',
})
function cancel() {
  drawer.value = false
}
async function getUserInfo(page = 1) {
  currentPage.value = page
  let result = await reqUserInfo(
    currentPage.value,
    pageSize.value,
    keyword.value,
  )
  if (result.code == 200) {
    userInfo.value = result.data.records
    total.value = result.data.total
  }
}

const handleCheckAllChange = (val: any) => {
  userRole.value = val ? allRole.value : []
  isIndeterminate.value = false
}

const handleCheckedCitiesChange = (value: any) => {
  const checkedCount = value.length
  checkAll.value = checkedCount === allRole.value.length
  isIndeterminate.value =
    checkedCount > 0 && checkedCount < allRole.value.length
}

function addUser() {
  drawer.value = true
  Object.assign(userParams, {
    id: undefined,
    username: '',
    name: '',
    password: '',
  })
  //清除上一次的错误的提示信息
  nextTick(() => {
    formRef.value.clearValidate('username')
    formRef.value.clearValidate('name')
    formRef.value.clearValidate('password')
  })
}

function editUser(row: User) {
  Object.assign(userParams, row)
  drawer.value = true
  //清除上一次的错误的提示信息
  nextTick(() => {
    formRef.value.clearValidate('username')
    formRef.value.clearValidate('name')
  })
}

async function save() {
  try {
    await formRef.value.validate()
  } catch (e) {
    ElMessage.error('请你输入符合校验规则的内容')
    return
  }
  let result = await reqAddOrUpdateUser(userParams)
  if (result.code == 200) {
    ElMessage.success(userParams.id ? '修改用户成功' : '添加用户成功')
    getUserInfo(userParams.id ? currentPage.value : 1)
    if (userParams.id) {
      try {
        await userStore.getUserInfo()
      } catch (e) {
        await userStore.logout()
        $router.replace({
          path: '/login',
          query: {
            redirect: $route.path,
          },
        })
      }
    }
  } else {
    ElMessage.error(userParams.id ? '修改用户失败' : '添加用户失败')
  }
  drawer.value = false
}

//校验用户名字回调函数
const validatorUsername = (_rule: any, value: any, callBack: any) => {
  //用户名字|昵称,长度至少五位
  if (value.trim().length >= 5) {
    callBack()
  } else {
    callBack(new Error('用户名字至少五位'))
  }
}
//校验用户名字回调函数
const validatorname = (_rule: any, value: any, callBack: any) => {
  //用户名字|昵称,长度至少五位
  if (value.trim().length >= 5) {
    callBack()
  } else {
    callBack(new Error('用户昵称至少五位'))
  }
}
const validatorPassword = (_rule: any, value: any, callBack: any) => {
  //用户名字|昵称,长度至少五位
  if (value.trim().length >= 6) {
    callBack()
  } else {
    callBack(new Error('用户密码至少六位'))
  }
}
//表单校验的规则对象
const rules = {
  //用户名字
  username: [{ required: true, trigger: 'blur', validator: validatorUsername }],
  //用户昵称
  name: [{ required: true, trigger: 'blur', validator: validatorname }],
  //用户的密码
  password: [{ required: true, trigger: 'blur', validator: validatorPassword }],
}

function handler() {
  getUserInfo()
}

async function setRole(row: any) {
  drawer1.value = true
  Object.assign(userParams, row)
  let result = await reqAllRole(row.id)
  if (result.code == 200) {
    allRole.value = result.data.allRolesList
    userRole.value = result.data.assignRoles
  }
}

//确定按钮的回调(分配职位)
const confirmClick = async () => {
  //收集参数
  let data: SetRoleData = {
    userId: userParams.id as number,
    roleIdList: userRole.value.map((item: any) => {
      return item.id as number
    }),
  }
  //分配用户的职位
  let result: any = await reqSetUserRole(data)
  if (result.code == 200) {
    //提示信息
    ElMessage({ type: 'success', message: '分配职务成功' })
    //关闭抽屉
    drawer1.value = false
    //获取更新完毕用户的信息,更新完毕留在当前页
    getUserInfo(currentPage.value)
  }
}

async function deleteUser(id: number) {
  let result = await reqRemoveUser(id)
  if (result.code == 200) {
    ElMessage.success('删除成功')
    getUserInfo(
      userInfo.value.length > 1 ? currentPage.value : currentPage.value - 1,
    )
  } else {
    ElMessage.success('删除失败')
  }
}

let selectUser = ref([])
function handleChange(row: any) {
  selectUser.value = row
}

async function patchDelete() {
  let patchIds = selectUser.value.map((item: any) => item.id)
  //批量删除的请求
  let result: any = await reqSelectUser(patchIds)
  if (result.code == 200) {
    ElMessage.success('删除成功')
    getUserInfo(
      userInfo.value.length > 1 ? currentPage.value : currentPage.value - 1,
    )
  } else {
    ElMessage.success('删除失败')
  }
}

function reset() {
  layoutStore.reflesh = !layoutStore.reflesh
}
</script>

<style scoped lang="scss">
.user-form {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
